<?php
namespace App\Http\Controllers\Business\Shop\V1;

use App\Models\Order;
use App\Models\Shop;
use App\Models\ShopEvent;
use App\Models\ShopUser;
use App\Models\ShopSalesman;
use App\Models\ShopContract;
use App\Models\Feedback;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Redis;
use App\Models\SmsMessage;

class PublicBusiness {
    //通过shopuserid获取商家列表
    public static function getShop($shopuserid) {
        if(!$shopuserid) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $auth = Redis::get('ShopAuth:'.$shopuserid);
        if(!$auth) {
            $auth = ShopUser::where('id', $shopuserid)->pluck('auth')->first();
        }
        $auth = json_decode($auth,true);
        $data = [];
        foreach ($auth as $k => $v) {
            array_push($data,Shop::where('id',$k)->select('id as shopid','name','address', 'status')->first());
        }
        return ['status'=>'success','data'=>$data];
    }

    public static function index($shopid, $shopuserid='') {
        if(!$shopid) {
            return ['status'=>'failed', 'message'=>'参数错误！'];
        }
        $shop = Shop::where('id',$shopid)->select('name','todayevent','nightevent','nextevent', 'maxsales', 'firstclassname', 'secondclassname', 'weekdoubleday', 'buynumber','invoice', 'notpartakegoods', 'content', 'status', 'parentmobile')->first();
        if(!$shop) {
            return ['status'=>'failed', 'message'=>'获取信息错误！'];
        }
        if($shop['todayevent'] || $shop['nightevent']) {
            $shop['ordernum'] = Order::where('shopid',$shopid)->where('created_at','>=',date('Y-m-d',time()).' 00:00:00')
                ->where('created_at','<=',date('Y-m-d',time()).' 23:59:59')->get()->count();
            $shop['ordersum'] = Order::where('shopid',$shopid)->where('created_at','>=',date('Y-m-d',time()).' 00:00:00')
                ->where('created_at','<=',date('Y-m-d',time()).' 23:59:59')->sum('shopamount');
            if($shop['ordersum'] == "") {
                $shop['ordersum'] = 0.00;
            }
            //除xxx外 全场参与 ，300元封顶，当天每个用户仅限1单
            if($shop['notpartakegoods']) {
                $tips = "除" . $shop['notpartakegoods'] . "外，全场参与，";
            } else {
                $tips = "全场参与，";
            }
            if($shop['maxsales'] != '0') {
                $tips .= $shop['maxsales'] . "元封顶，";
            }
            if($shop['buynumber'] == '0') {
                $tips .= "当天每个用户不限买单次数";
            } else {
                $tips .= "当天每个用户仅限" . $shop['buynumber'] . "单";
            }
            $shop['tips'] = $tips;
        }
        if(ShopEvent::where('shopid',$shopid)->where('event','>',date('Y-m-d',time()))->first()) {
            $shop['doublecalendar'] = '1';
        } else {
            $shop['doublecalendar'] = '0';
        }
        $shopParentMobile = $shop['parentmobile'];
        $shop['ischild'] = 1;
        $shop['issalesman'] = 0;
        $shop['ispartnersalesman'] = 0;
        $shopSalesman = ShopSalesman::where('shopid', $shopid)->select('type')->first();
        if($shopSalesman) {
            $shop['issalesman'] = 1;
            if($shopSalesman['type'] == 'partner') {
                $shop['ispartnersalesman'] = 1;
            }
        }
        if(ShopUser::where('id', $shopuserid)->pluck('mobile')->first() == $shopParentMobile) {
            $shop['ischild'] = 0;
        }
        $shopContract = ShopContract::where('shopid', $shopid)->orderBy('id', 'desc')->select('starttime', 'lasttime')->first();
        if($shopContract) {
            $shop['contractstarttime'] = $shopContract['starttime'];
            $shop['contractlasttime'] = $shopContract['lasttime'];
        } else {
            $shop['contractstarttime'] = '0000-00-00';
            $shop['contractlasttime'] = '0000-00-00';
        }
        //地推二维码
        //$shop['qrcodeurl'] = env('WEB_URL') . "mobile/salesman/gotodownApp?shopid=" . $shopid . "&shopuserid=" . $shopuserid . "&shopname=". urlencode($shop['name']);
        $shop['qrcodeurl'] = env('WEB_URL') . "qrcode/shop/" . $shopid . "?shopuserid=" . $shopuserid;
        return ['status'=>'success','data'=>$shop];
    }

    public static function doubleCalendarList($shopid) {
        $data = ShopEvent::where('shopid',$shopid)->select('event')->get();
        return ['status'=>'success','data'=>$data];
    }
    //通过商家id，商家管理者id来获取权限
    public static function getAuth($shopuserid, $shopid) {
        if(!$shopid || !$shopuserid) {
            return ['status'=>'failed', 'message'=>'参数错误！'];
        }
        $auth = Redis::get('ShopAuth:'.$shopuserid);
        if(!$auth) {
            $auth = ShopUser::where('id', $shopuserid)->pluck('auth')->first();
            Redis::set('ShopAuth:'.$shopuserid,$auth);
        }
        $autharray = json_decode($auth, true);
        $data = [];
        if(isset($autharray[$shopid])) {
            $data = $autharray[$shopid];
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //个人信息
    public static function getUserInfo($shopUserId) {
        if(!$shopUserId) {
            return ['status'=>'failed', 'message'=>"参数错误！"];
        }
        $shopUser = ShopUser::where('id', $shopUserId)->select('name', 'mobile', 'auth','password')->first();
        if(!$shopUser) {
            return ['status'=>'failed', 'message'=>'获取失败！'];
        }
        if(!empty($shopUser['password'])){
            $passStatus = 1;
        }else{
            $passStatus = 0;
        }
        $auth = json_decode($shopUser['auth'], true);
        $lists = [];
        foreach ($auth as $k => $v) {
            $shop = Shop::where('shops.id',$k)
                ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
                ->select('shops.id', 'shops.name', 'shops.address', 'shops.status', 'shops.parentmobile', 'admin_users.realname as managername', 'admin_users.mobile as managermobile')->first();
            if($shop) {
                array_push($lists, $shop);
            }
        }
        $data = [
            'name' => $shopUser['name'],
            'mobile' => $shopUser['mobile'],
            'passwordstatus'=>$passStatus,
            'shoplists' => $lists,
        ];
        return ['status'=>'success', 'data'=>$data ];
    }

    //添加或者修改商家的登录密码
    public static function updateUserPassword($shopUserId,$code,$password,$confirmPassword){
        if(!$shopUserId){
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(!$code){
            return ['status'=>'failed', 'message'=>'请输入验证码'];
        }
        if(!$password || !$confirmPassword){
            return ['status'=>'failed', 'message'=>'请输入密码'];
        }
        if($password != $confirmPassword) {
            return ['status'=>'failed', 'message'=>'两次密码不一致'];
        }
        if(!preg_match('/^[0-9a-zA-Z_#]{6,16}$/',$password) && !preg_match('/^[0-9a-zA-Z_#].{6,16}$/',$password)){ //匹配
            return ['status'=>'failed', 'message'=>'密码不是6-16位字符'];
        }
        $shopUser = ShopUser::where('id', $shopUserId)->first();
        if(!$shopUser) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        if(!SmsMessage::loginIdentifyingCodeVerify($shopUser->mobile, $code, '2')) {
            return ['status'=>'failed', 'message'=>'验证码错误'];
        }
        $shopUser->password = md5($password . env('PASSWORD_SALT'));
        $shopUser->save();
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //意见反馈
    public static function feedback($shopuserid, $content, $type='shop', $osVersion='', $phoneType='', $versionCode='',$shopId='') {
        if(!$shopuserid||!$content||!$type) {
            return ['status'=>'failed', 'message'=>"参数错误！"];
        }
        $shopuser = ShopUser::where('id', $shopuserid)->first();
        if(!$shopuser) {
            return ['status'=>'failed', 'message'=>'提交失败！'];
        }
        //判断shopid是否为空,为空就去shop_user表中获取第一个商家的shopid
        if(!$shopId){
            $shopIdArr = explode(',',$shopuser['shopid']);
            $shopId = $shopIdArr['0'];
        }
        $username = $shopuser['name'];
        $mobile = $shopuser['mobile'];
        $feedback = Feedback::create([
            'userid' => $shopuserid,
            'username' => $username,
            'mobile' => $mobile,
            'type' => $type,
            'content' => $content,
            'status' => 0,
            'osversion' => $osVersion,
            'phonetype' => $phoneType,
            'versioncode' => $versionCode,
            'shopid'=>$shopId,
            'cityid'=>1
        ]);
        $feedback->save();
        return ['status'=>'success', 'message'=>'提交成功！'];
    }
}